import { Button, Icon, Card, Modal, notification } from 'antd'
import React, { useState, useEffect, useRef, useCallback } from 'react';
import router from 'umi/router'
import { wrappedComponentRef } from 'rc-form'; //该方法 返回HOC的ref引用
import styles from './index.less';
import { connect } from 'dva';
import { useRequest } from '@umijs/hooks';
import { getFlightPaxInfo, saveOrderInfo } from '../service';
import { passengersSortFun } from '@/utils/passengersSort'; // 调用排序函数
const { confirm } = Modal;

import BasisMes from '../components/AuditTables/BasisMes'
import PassengerListTable from '../components/AuditTables/PassengerListTable'// 旅客维护列表弹框组件
import CompensationStandard from '../components/AuditTables/CompensationStandard'
import PaymentMethod from '../components/AuditTables/PaymentMethod'
import PassengerMaintain from '../components/AuditTables/PassengerMaintain'
import AuditProgress from '../components/AuditTables/AuditProgress'
import PassengerList from '../components/AuditTables/PassengerList'
import Title from '../components/AuditTables/Title' // 标题
import SuccessModal from '../components/AuditTables/SuccessModal'
import AuditModal from '../components/AuditTables/AuditModal' // 审核弹框
import ObjectOfApproval from '../components/AuditTables/ObjectOfApproval' // 审核部门
import AuthComponent from '@/components/Authorized/AuthComponent';


const AuditDetail = (props) => {
  const { location: { state } } = props;
  const handleStandardRef = useRef(); //补偿标准的ref引用
  const submitTypeRef = useRef('0'); //提交类型-提交(1)还是保存（0）
  // const [orderId, handleOrderId] = useState('')
  const [successModalVisible, handleSuccessModalVisible] = useState(false) //展示审核成功弹框
  const [passengerListTableShow, handlePassengerListTableShow] = useState(false) //展示航班数据
  const [amount, setAmount] = useState(200) //收款方式的金额
  const [isTable, handleTable] = useState(false); // 旅客列表收缩展开
  const [inited, setInited] = useState(true)   // 防止多次请求


  const [orderDetailInfo, handleOrderDetailInfo] = useState({}) // 基本信息
  const [eCompensateInfo, handlECompensateInfo] = useState([]) // 补偿标准
  const [allPassengersList, setAllPassengersList] = useState([]) // 所有旅客列表
  const [checkedPaxList, handelCheckedPaxList] = useState([]); // 已选旅客列表

  const [pageInitData, setPageInitData] = useState({}) // 路由过来的数据
  useEffect(() => { //获取路由传过来的数据
    if (inited) {
      // 设置页面的初始数据
      let initState = state ? state.selectRow[0] : {};
      if (JSON.stringify(initState) == '{}' || !initState) {
        notification.info({
          description: '页面参数不能为空',
          message: '系统提示',
        });
        unCache();
      }
      setPageInitData(initState);
    } else {
      setInited(false)
    }
  }, [state])

  // 获取航班旅客列表
  const { loading: getFlightPaxInfoLoading, run: getPassengersList } = useRequest((params) => getFlightPaxInfo(params),
    {
      manual: true,
      onSuccess: (resData) => {
        if (!resData) return;
        let _list = passengersSortFun(resData, 'psgName', 'idNum', 'etNum');
        setAllPassengersList(_list || []); //设置所有旅客列表数据 
        handlePassengerListTableShow(true); // 打开旅客列表弹框
      }
    })

  // 补偿标准获取数据
  const handleValues = (val) => {
    if (typeof val === "object") {
      // 获取补偿标准的数据
      let currentAmount = 0;
      for (let item of props.passengers) {
        // todo 这里不精确运算的bug
        if (val.spread == '0') {
          currentAmount = item.isChild === 'N' ? 
            (item.withBaby === 'N' ? val.businessClass : (Number((val.businessClass * val.babyRatio) / 100) + Number(val.businessClass))) : 
            (val.businessClass * val.childRatio) / 100;
        }else{
          currentAmount = val.spread
        }
        item.paxId = item.idx;
        item.paxName = item.psgName;
        item.idNo = item.idNum;
        item.sex = item.gender;
        item.telephone = item.phone;
        item.orgCityAirp = item.orig;
        item.dstCityAirp = item.dest;
        item.tktNo = item.etNum;
        item.tktDate = item.printTicketTime;
        item.currentAmount = currentAmount;
      }
      // 拼接参数
      let req_params = {
        // 基本信息
        "orderInfo": {
          "flightId": pageInitData.id, //航班id
          "flightNo": pageInitData.flightNumber, //航班号
          "flightDate": pageInitData.flightDate, //航班日期
          "acType": pageInitData.fltCode, //机型
          "std": pageInitData.std, //计划起飞时间
          "sta": pageInitData.sta, //计划到达时间
          "etd": pageInitData.etd, //预计起飞时间
          "dst": pageInitData.dst, //到达航站
          "org": pageInitData.org, //起飞航站
          "planeCode": pageInitData.planecode, //飞机号
          "lateReason": pageInitData.lateReason, //延误原因
          "payType": '0', //补偿类型-不正常航班补偿
          "serviceCity": props.baseData.serviceTerminal, //航站
          "delayTime": props.baseData.delayTime * 60, //延误时长-秒
          "paymentClass": props.payMethods?.payMethods?.join(''), //补偿类型可选范围（1-线上支付 2-优惠券 同时传同时有）
          "choiceSegment": `${pageInitData.orgName}-${pageInitData.dstName}`,//航段
          "status": submitTypeRef.current, //提交(1)还是保存（0）
          "remark":props.remark // 旅客维护的备注
        },
        // 补偿标准
        "compensateInfoList": val.spread == '0' ?  [
          { "cpsNum": val.businessClass, "babyStd": val.babyRatio, "childStd": val.childRatio, "classType": "1", "activityCode": props.payMethods?.payMethods?.length > 1 ? props.payMethods?.coupon : null }, //经济舱
          { "cpsNum": val.businessClass, "babyStd": val.babyRatio, "childStd": val.childRatio, "classType": "2", "activityCode": props.payMethods?.payMethods?.length > 1 ? props.payMethods?.coupon : null }, //公务/头等舱
        ] : [
          { "cpsNum": val.spread, "babyStd": 0, "childStd": 0, "classType": "3", "activityCode": props.payMethods?.payMethods?.length > 1 ? props.payMethods?.coupon : null }, //自定义金额
        ],
        // 旅客信息
        "paxInfoList": props.passengers,
      }
      submitFun(req_params);
    } else {
      setAmount(val); //同步补偿金额
    }
  }
  // 解除dva中的数据缓存
  const unCache = (val) => {
    props.dispatch({
      type: 'auditDetail/resetUploadList'
    });
    props.dispatch({
      type: 'auditDetail/removeTabs',
      payload: { 
        removeTabsPathname:props.location.pathname
      }
    });
    let to_url;
    if (val === 'operate') {
      to_url = '/compensation/indemnitySheet';
    }else{
      to_url = window.localStorage.getItem('usualMonitorBackUrl') || '/usualMonitor/usualMonitor';
    };
    router.push(to_url);
  }
  // 提交保存的函数
  const { run: submitFun, loading } = useRequest((params) => {
    return saveOrderInfo(params);
  },
    {
      manual: true,
      onSuccess: (data) => {
        if (data) {
          notification.success({
            message: '提示',
            description: submitTypeRef.current == '1' ? '补偿单创建成功' : '保存成功',
          });
          unCache('operate');
        }
      }
    }
  );

  // 补偿标准验证表单
  const handleStandard = (type) => {
    if (type === '1' && props.passengers.length === 0) {
      return notification.warning({
        message: '提示',
        description: '补偿标准或者自定义金额至少一项不为空, 已选旅客不能为空',
      });
    }
    submitTypeRef.current = type;
    // 调用补偿标准组件的表单验证方法
    handleStandardRef.current.handleSubmit();
  }

  const handleModalVisible = val => {
    handlePassengerListTableShow(val);
  }
  // 已选旅客列表的显示
  const toggleTable = () => {
    isTable ? handleTable(false) : handleTable(true);
  }

  const FooterButton = () => {
    return (
      <p className={styles.buttons}>
        {/* <AuthComponent authCode="compensation.audit.auditOp"> */}
        <Button
          loading={loading}
          type='primary'
          onClick={() => { handleStandard("1") }}>提交</Button>
        {/* </AuthComponent> */}

        <Button loading={loading} onClick={() => { handleStandard("0") }}>保存</Button>

        <Button onClick={() => {
          confirm({
            title: '关闭将不保存补偿单数据, 确认关闭吗？',
            onOk() {
              unCache('close')
            },
            onCancel() { },
          });

        }}>取消</Button>
      </p>
    )
  }

  return (
    <div className={styles.main}>
      <Title title='基本信息'></Title>
      <BasisMes allDatas={pageInitData} />
      <Title title='补偿标准'></Title>
      <CompensationStandard allDatas={pageInitData} wrappedComponentRef={handleStandardRef} handleValues={handleValues}></CompensationStandard>
      <Title title='收款方式'></Title>
      <PaymentMethod allDatas={pageInitData} amount={amount}></PaymentMethod>
      <Title title='旅客维护'>
        <Button type='primary' loading={getFlightPaxInfoLoading} onClick={() => {
          return getPassengersList({
            dest: pageInitData.ccode ? ((pageInitData.org === pageInitData.bcode) ? pageInitData.dst : "") : pageInitData.dst, //起始航班, //到达航站
            flightNumber: pageInitData.flightNumber, //航班号
            orig: pageInitData.ccode ? ((pageInitData.org === pageInitData.acode) ? pageInitData.org : "") : pageInitData.org, //起始航班
            flightStartDate: pageInitData.flightDate, //航班起始日期
            flightEndDate: pageInitData.flightDate, //航班到达日期
            isCancel: "N", //是否取消 默认是
            isPrintTktNo: "Y", //是否出票 默认是
            current: 1,
            pageSize: 1000,
          });
        }}><Icon type="edit" />旅客维护</Button>
      </Title>
      <PassengerMaintain></PassengerMaintain>

      {/* 旅客维护列表弹框 */}
      <PassengerListTable
        allDatas={pageInitData}
        allPassengersList={allPassengersList}
        passengerListTableShow={passengerListTableShow}
        getFlightPaxInfoLoading={getFlightPaxInfoLoading}
        getPassengersList={getPassengersList}
        handleModalVisible={handleModalVisible}>
      </PassengerListTable>

      <div onClick={toggleTable} className={styles.passengerTitle}>
        <Title title="已选旅客列表" />
        <Icon type={isTable ? "caret-down" : "caret-right"} />
      </div>
      {/* 旅客列表 */}
      <Card className={isTable ? styles.showTable : styles.hideTable}>
        <PassengerList checkedPaxList={props.passengers}></PassengerList>
      </Card>

      {/* 操作按钮 */}
      <FooterButton></FooterButton>


      {/* <Title title='审核流程'></Title> */}
      {/* <AuditProgress auditProgressData={auditProgressData}></AuditProgress> */}


      {/* 审核弹框 */}
      {/* <AuditModal
          auditData={auditData}
          auditModalVisible={auditModalVisible} 
          onClose={() => {
            handleAuditModalVisible(false);
          }}
          onSuccess={(res) => {
            handleAuditModalVisible(false)
            handleSuccessModalVisible(true)
          }}
          onNext={(res)=>{
            handleApprovalVisible(true)
            handleAuditModalVisible(false)
            handleApprovalData(res)
          }}
          ></AuditModal> */}

      {/* 审核弹框第二步-选择部门 */}
      {/* <ObjectOfApproval
          approvalData={approvalData}
          approvalVisible={approvalVisible}
          handleApprovalVisible={handleApprovalVisible}
          onClose={() => {
            handleApprovalVisible(false);
          }}
          onSuccess={(res) => {
            handleApprovalVisible(false)
            handleSuccessModalVisible(true)
          }}
          ></ObjectOfApproval> */}

      {/* 成功弹框 */}
      <SuccessModal
        onClose={() => {
          handleSuccessModalVisible(false)
          router.push('/compensation/CompensationAudit')
        }}
        successModalVisible={successModalVisible}
      ></SuccessModal>
    </div>
  );
};

export default connect(state => state.auditDetail)(AuditDetail);

